#!/bin/bash

# 输出文件
INSTALLED_PACKAGES="installed_packages.txt"
INSTALL_SCRIPT="install_packages.sh"

# 获取已安装的软件包列表
dpkg --get-selections | awk '{print $1}' > "$INSTALLED_PACKAGES"

# 开始编写安装脚本
cat << 'EOF' > "$INSTALL_SCRIPT"
#!/bin/bash
set -e

LOG_FILE="installation_log.txt"
ERROR_LOG="installation_errors.log"

# 清空旧日志文件
> "$LOG_FILE"
> "$ERROR_LOG"

# 定义要安装的软件包列表
PACKAGES=(
EOF

# 添加已安装的软件包到数组
while read -r package; do
  echo "  \"$package\"" >> "$INSTALL_SCRIPT"
done < "$INSTALLED_PACKAGES"

# 继续编写安装脚本
cat << 'EOF' >> "$INSTALL_SCRIPT"
)

TOTAL_PACKAGES=${#PACKAGES[@]}
CURRENT_COUNT=0
ERROR_PACKAGES=()

# 检查包是否已安装的函数
check_installed() {
  dpkg -l | grep -q "^ii\s\+$1\s"
}

# 安装软件包的函数
install_package() {
  local package=$1
  local current_count=$2
  local progress_length=50
  local progress_char="="
  local progress_bar=""

  # 计算进度条
  local progress_percentage=$((current_count * 100 / TOTAL_PACKAGES))
  local progress_chars=$((progress_length * current_count / TOTAL_PACKAGES))

  # 构建进度条
  progress_bar=$(printf "%-${progress_length}s" | tr ' ' "$progress_char")
  progress_bar=${progress_bar:0:progress_chars}

  # 输出进度信息，不换行
  if ! sudo apt-get install -y $package >> "$LOG_FILE" 2>&1; then
    ERROR_PACKAGES+=("$package")
    # 更新进度条，显示失败信息
    printf "\r%-${progress_length}s [失败:$package] %d%%" "$progress_bar" "$progress_percentage"
    echo -e "\n$package 安装失败 ($current_count/$TOTAL_PACKAGES)." | tee -a "$ERROR_LOG"
  else
    # 更新进度条，显示成功信息
    printf "\r%-${progress_length}s [成功:$package] %d%%" "$progress_bar" "$progress_percentage"
    # 将成功信息追加到日志文件
    echo "$package 安装成功 ($current_count/$TOTAL_PACKAGES)." >> "$LOG_FILE"
  fi
}

# 遍历每个包名并执行安装
for package in "${PACKAGES[@]}"; do
  CURRENT_COUNT=$((CURRENT_COUNT + 1))
  if ! check_installed $package; then
    install_package $package $CURRENT_COUNT
  else
    # 如果已经安装，则更新进度条，显示已安装信息
    progress_percentage=$((CURRENT_COUNT * 100 / TOTAL_PACKAGES))
    progress_bar=$(printf "%-${progress_length}s" | tr ' ' '-')
    progress_bar=${progress_bar:0:$((progress_length * CURRENT_COUNT / TOTAL_PACKAGES))}
    printf "\r%-${progress_length}s [已安装:$package] %d%%" "$progress_bar" "$progress_percentage"
    # 将已安装信息追加到日志文件
    echo "$package 已经安装。 ($CURRENT_COUNT/$TOTAL_PACKAGES)." >> "$LOG_FILE"
  fi
done

# 输出错误信息
if [ ${#ERROR_PACKAGES[@]} -ne 0 ]; then
  echo -e "\n安装失败的软件包如下:"
  for pkg in "${ERROR_PACKAGES[@]}"; do
    echo "$pkg"
  done
else
  echo -e "\n所有软件包安装成功。"
fi

echo -e "\n软件包安装完成。请检查 $LOG_FILE 和 $ERROR_LOG 获取详细信息。"
EOF

# 给予执行权限
chmod +x "$INSTALL_SCRIPT"
echo "安装脚本已生成: $INSTALL_SCRIPT"
echo "请运行 ./$INSTALL_SCRIPT 开始安装软件包"
